package org.test.netty;

import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.test.constants.WsConstant;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * websocket连接通道管理器
 */

public class WebScocketChannelGroup {
	 private  final static Logger log=LoggerFactory.getLogger(WebScocketChannelGroup.class);
	 public  static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup("WsChannelGroups", GlobalEventExecutor.INSTANCE);
		
	 /**
	  * 添加channel
	  * @param channel
	  */
	 public static void add(Channel channel) {
		String userId = channel.attr(WsConstant.USER_ID_KEY).get();
		Channel oldChannel = null;	
		try {
			oldChannel = WebScocketChannelGroup.find(userId);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		if(oldChannel != null) {
			WebScocketChannelGroup.discard(oldChannel);
		}
        CHANNEL_GROUP.add(channel);
    	JSONObject board = new JSONObject();
    	board.put("userOnlines", CHANNEL_GROUP.size());
        WebScocketChannelGroup.broadCast(board.toJSONString());
        log.info("userId:"+userId+"登录成功");
        log.info("总在线人数"+CHANNEL_GROUP.size());
 }
	 
	 /**
	  * 移除channel
	  * @param channel
	  * @return
	  */
	 public static boolean discard(Channel channel) {
		 	channel.close();
		    String userId = channel.attr(WsConstant.USER_ID_KEY).get();
	        boolean result = CHANNEL_GROUP.remove(channel);
	        JSONObject board = new JSONObject();
	    	board.put("userOnlines", CHANNEL_GROUP.size());
	        WebScocketChannelGroup.broadCast(board.toJSONString());
	        log.info("userId:"+userId+"logout");
	        log.info("总在线人数"+CHANNEL_GROUP.size());
	        return result;
	 }
	 
	 /**
	  * 根据用户id获取连接
	  * @param userId
	  * @return
	  */
	 public static Channel find(String userId) {
	     Iterator<Channel> iteraotr =   WebScocketChannelGroup.CHANNEL_GROUP.iterator();
	     boolean flag = true; 
	 	 Channel current = null;
	 	 String currentUserId =null;
	        while(iteraotr.hasNext() && flag){
	        	current = iteraotr.next();
	        	currentUserId = current.attr(WsConstant.USER_ID_KEY).get();
	        	if(userId.equals(currentUserId) ){
	        		flag = false;
	        	}else {
	        		current = null;
	        	}
	        }
	     return current;
	 }
	 
	 /**
	  * 给某个用户发送消息
	  * @param sendTo
	  * @param msg
	  * @param sendFrom
	  * @return
	  */
	 public static boolean send(String sendTo,String msg,String sendFrom){
		 Channel channel= find(sendTo);
		 if(channel != null){
			 JSONObject sendData = new JSONObject();
			 sendData.put("msg",msg);
			 sendData.put("sendFrom",sendFrom);
			 channel.writeAndFlush(new TextWebSocketFrame(sendData.toJSONString()));
			 return true;
		 }
		 return false;
	 }
	 
	 /**
	  * 发送广播
	  * @param msg
	  * @return
	  */
	 public static boolean broadCast(String msg) {
		 return CHANNEL_GROUP.writeAndFlush(new TextWebSocketFrame(msg)).isDone();
	 }
	 
	 
	    
}
